﻿using Business;
using Business.Service;
using Model;
using Newtonsoft.Json;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using WoChu.Infrastructure.Web;

namespace MvcAppWeb.Controllers
{
    public class InitStockController : BaseDataController
    {
        public ActionResult InitStock()
        {
            if (Session["UserInfo"] == null) return RedirectToAction("LogOn", "Account");
            else
            {
                AppUserList model = (AppUserList)Session["UserInfo"];
                return View(model);
            }
        }

        /// <summary>
        /// 初始化数据
        /// </summary>
        /// <param name="goodsBatchCode"></param>
        /// <param name="locationCode"></param>
        /// <param name="goodsCode"></param>
        /// <param name="goodsName"></param>
        /// <returns></returns>
        public JsonResult InitJsonResult(string goodsBatchCode, string goodsCode)
        {
            int page = int.Parse(Request["page"].ToString());
            int rows = int.Parse(Request["rows"].ToString());
            int total = 0;
            string where = " ";
            if (!string.IsNullOrEmpty(goodsBatchCode))
            {
                where += @" and Goodscode='" + goodsBatchCode + "'";
            }
            if (!string.IsNullOrEmpty(goodsCode))
            {
                where += " and goods_sn='" + goodsCode + "'";
            }

            BInitStock bi = new BInitStock();
            var result = bi.GetInitStockList(1, 5000, out total, where);
            Session["OnlineSysList"] = result;
            Dictionary<string, object> json = new Dictionary<string, object>();
            json.Add("total", total);
            json.Add("rows", result);
            return Json(json, JsonRequestBehavior.AllowGet);
        }


        [HttpPost]
        public FileResult ExportExcel(int page, int rows)//导出execl
        {
            //创建Excel文件的对象
            HSSFWorkbook book = new HSSFWorkbook();
            //添加一个sheet
            ISheet sheet1 = book.CreateSheet("Sheet1");
            #region 获取list数据
            int total = 0;
            string goodsBatchCode = Request["txtGOODSBATCHCODE"];
            string locationCode = Request["txtLOCATIONCODE"];
            string goodsCode = Request["txtGOODSCODE"];
            string goodsName = Request["txtGOODSNAME"];


            string where = " ";
            if (!string.IsNullOrEmpty(goodsBatchCode))
            {
                where += @" and T1.GOODSBATCHCODE like'%" + goodsBatchCode + "%'";
            }
            if (!string.IsNullOrEmpty(locationCode))
            {
                where += " and T7.LOCATIONCODE like'%" + locationCode + "%'";
            }
            if (!string.IsNullOrEmpty(goodsCode))
            {
                where += " and T2.GOODSCODE like'%" + goodsCode + "%'";
            }
            if (!string.IsNullOrEmpty(goodsName))
            {
                where += " and T2.GOODSNAME like'%" + goodsName + "%'";
            }
            BLocationInventory nc = new BLocationInventory();
            List<LocationInventoryInfo> list = nc.GetLocationInventoryList(page, int.MaxValue, out total, where);
            #endregion
            //给sheet1添加第一行的头部标题
            IRow row1 = sheet1.CreateRow(0);
            List<string> lstTitle = new List<string>{ "商品批次号", "货位编码", "商品编码", "商品名称"
                , "仓库", "库位", "生产日期", "保质天数"
                , "库存数" , "单位"  , "采购单位库存"  , "有效天数" , "换算系数" };
            for (int i = 0; i < lstTitle.Count; i++)
            {
                row1.CreateCell(i).SetCellValue(lstTitle[i]);
            }
            //将数据逐步写入sheet1各个行
            for (int i = 0; i < list.Count; i++)
            {
                IRow rowtemp = sheet1.CreateRow(i + 1);
                rowtemp.CreateCell(0).SetCellValue(list[i].GOODSBATCHCODE);
                rowtemp.CreateCell(1).SetCellValue(list[i].LOCATIONCODE);
                rowtemp.CreateCell(2).SetCellValue(list[i].GOODSCODE);
                rowtemp.CreateCell(3).SetCellValue(list[i].GOODSNAME);
                rowtemp.CreateCell(4).SetCellValue(list[i].WAREHOUSENAME);
                rowtemp.CreateCell(5).SetCellValue(list[i].CELLNO);
                rowtemp.CreateCell(6).SetCellValue(list[i].PRODUCTIONDATE);
                rowtemp.CreateCell(7).SetCellValue(list[i].EXPIRYDAYS);
                rowtemp.CreateCell(8).SetCellValue(list[i].QTY.ToString());
                rowtemp.CreateCell(9).SetCellValue(list[i].UNITNAME);
                if (list[i].PURQTY > 0)
                {
                    rowtemp.CreateCell(10).SetCellValue(list[i].PURQTY.ToString() + list[i].PURUNITNAME);
                }
                else
                {
                    rowtemp.CreateCell(10).SetCellValue("");

                }

                rowtemp.CreateCell(11).SetCellValue(GetValidDay(list[i].PRODUCTIONDATE, list[i].EXPIRYDAYS));
                rowtemp.CreateCell(12).SetCellValue(list[i].PURUNITQTY.ToString());
            }
            // 写入到客户端 
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            book.Write(ms);
            ms.Seek(0, SeekOrigin.Begin);
            return File(ms, "application/vnd.ms-excel", NewTimeStamp("LocationInventory"));
        }

        public string NewTimeStamp(string strFileName)
        {
            //生成文件名: 当前年月日小时分钟秒+ 随机数
            Random rd = new Random(int.Parse(DateTime.Now.ToString("MMddhhmmss")));
            strFileName += DateTime.Now.ToString("yyyyMMdd")
                + DateTime.Now.Hour
                + DateTime.Now.Minute
                + DateTime.Now.Second
                + rd.Next(999999).ToString()
                + ".xls";
            return strFileName;
        }

        public string GetValidDay(string PRODUCTIONDATE, int EXPIRYDAYS)
        {
            try
            {
                var PRODUCTIONYEAR = int.Parse(PRODUCTIONDATE.Substring(0, 1));
                var PRODUCTIONMONTH = int.Parse(PRODUCTIONDATE.Substring(1, 2));
                var PRODUCTIONDAY = int.Parse(PRODUCTIONDATE.Substring(3, 2));
                var date = DateTime.Now;
                var year = int.Parse(date.Year.ToString().Substring(3, 1));
                var month = date.Month;
                var day = date.Day;
                var pastdate = (year - PRODUCTIONYEAR) * 365 + (month - PRODUCTIONMONTH) * 30 + (day - PRODUCTIONDAY);
                if (pastdate >= 0 && EXPIRYDAYS - pastdate > 0)
                {
                    return (EXPIRYDAYS - pastdate).ToString();
                }
                else
                {
                    return "0";
                }
            }
            catch
            {
                return "0";
            }
        }

        /// <summary>
        /// 初始化在线库存
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string InitOnlineStock()
        {

            string url = ConfigSetting.GetConfigValueByName<string>("SysOnline.Path");
            int maxNum = ConfigSetting.GetConfigValueByName<int>("SysOnline.MaxNum");
            string sjson = string.Empty;
            List<OnlineStockInfo> listOS = (List<OnlineStockInfo>)Session["OnlineSysList"];
            //if (listOS.GroupBy(x => x.goods_sn).Count() > maxNum)
            //{
            //    sjson = "{hasError:true,error:'每次同步不大于" + maxNum.ToString() + "个成品！'}";
            //}
            //else
            //{
            try
            {
                //string url = "http://appapi.onlinestock.cn/api/ErpStock/InsertErpStock";
                //string url = "http://58.247.11.230:9099/api/ErpStock/InsertErpStock"; //测试IP地址
                //string url = "http://os.wochu.cn/api/ErpStock/InsertErpStock";
                //string url = "http://121.43.182.229/api/ErpStock/InsertErpStock";     //正式IP地址
                url = url + "/api/ErpStock/InsertErpStock";
                string josnData = JsonConvert.SerializeObject(listOS).ToString();
                ClientChannel cc = new ClientChannel();
                sjson = cc.Post(josnData, url);
            }
            catch (Exception ex)
            {
                sjson = "{hasError:true,error:'同步失败：" + ex.Message + "'}";
            }
            //}

            return sjson;

        }


    }
}
